<template>
	<view>
		<custom-navigation-bar title="商家申请"></custom-navigation-bar>
		<view class="main">
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						姓名
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.name" type="text" class="form-item-input" placeholder="请输入姓名"  />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
					<!-- <view class="form-item-error">21321</view> -->
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						性别
					</view>
					<view class="form-item-countent">
						<radio-group @change="updateSex" style="margin-top: 20rpx;"  >
							<lable v-for="(item,index) in sexArr" :key="index">
								<radio :value="item.value" class="custom-radio" :checked="item.value==applicationContent.sex" />{{item.name}}
							</lable> 
						</radio-group>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						联系电话
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.phone" type="text" class="form-item-input" placeholder="请输入联系电话" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						申请区域
					</view>
					<view class="form-item-countent"> 
						<picker class="position-picker" mode="region" @change="regionChange">
						    <view class="text">{{ region }} </view>
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						详细地址
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.position" type="text" class="form-item-input" placeholder="请输入详细地址" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			 
			<view class="form-item" style="border: none;height: 400rpx;">
				<view class="form-item-1" style="border: none;height: auto;"> 
					<map @click="selectAddress" style="height: 400rpx;width: 100%;" :longitude="longitude" :latitude="latitude" >
					</map>
				</view>
			</view>
			
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						服务范围
					</view>
					<view class="form-item-countent">
						<picker @change="serviceChange" :range="serviceArray" >
							<view style="padding: 20rpx;background-color: white;">{{ service }}</view>
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						选择模块
					</view>
					<view class="form-item-countent">
						<picker model='selector' @change="menuChange" :range="menuArr" range-key="name" >
							<input type="text" class="picker" :value="menu" placeholder="请选择模块" disabled/>
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						机构标签
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.tags" type="text" class="form-item-input" placeholder="请输入标签"  />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						法人姓名
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.legalPersonName" type="text" class="form-item-input" placeholder="请输入法人姓名"  />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						法人身份证号
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.legalPersonIdCard" type="text" class="form-item-input" placeholder="请输入法人身份证号"  />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker @select="handleIdSelect" @delete="handleIdDelete" limit="2" v-model="idImageFiles"
						title="请上传身份证反正面照片(最多2张)">
					</uni-file-picker>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						商户名称
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.shopName" type="text" class="form-item-input" placeholder="请输入商户名称"   />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						营业执照编码
					</view>
					<view class="form-item-countent">
						<input type="text" v-model="applicationContent.license" class="form-item-input" placeholder="请输入营业执照编码" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker @select="handleLicenseSelect" @delete="handleLicenseDelete" limit="1" v-model="licenseImage"
						title="请上传营业执照(最多1张)" ></uni-file-picker>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker fileType="image" @select="handleShopImageSelect" @delete="handleShopImageDelete" limit="1" v-model="shopImage"
						title="请上传门店照(最多1张)" ></uni-file-picker>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						开户行
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.bankName"  type="text" class="form-item-input" placeholder="请输入银行名称" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						银行卡号
					</view>
					<view class="form-item-countent">
						<input v-model="applicationContent.bankCard" type="text" class="form-item-input" placeholder="请输入银行卡号"  />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker limit="5" title="请上传附件照片(最多选择5个)" @select="handleFileSelect" v-model="fileImage"
						@delete="handleFileDelete"></uni-file-picker>
				</view>
			</view>
			<view class="form-item" style="border: none;">
				<view class="form-item-1" style="margin-top: 20rpx;font-size: 25rpx;border: none;" >
					<switch type="checkbox" checked="{{xieYiV}}" @change="xieYi"/>同意遵守<label style="color: blue;" @click="xieYiDetail">《商户入驻协议》</label>
				</view>
			</view>
			 
			<view class="form-item"  >
				<view style="width: 84%;float: left;margin-left: 8%;margin-top: 50rpx;margin-bottom: 60rpx;">
					<view class="btn" @click="submit">确定</view>
				</view>
			</view>
			 
		</view>
	</view>
</template>

<script setup>
	import CustomNavigationBar from '@/components/CustomNavigationBar.vue'
	 const xieYiV=ref(false);
	 function xieYi(e){
	 	console.log( e.detail.value);
	 	xieYiV.value=e.detail.value
	 }
	 function xieYiDetail(){
	 	uni.navigateTo({
	 		url: "/pages/protocol/shop"
	 	});
	 }
	import {
		defineComponent
	} from 'vue';
	import http from '../../utils/http';
	var sexArr=ref([
		{
			value:0,
			name:'男'
		},
		{
			value:1,
			name:'女'
		}
	]);
	import {
		onLoad,
	  	onPageScroll
	} from '@dcloudio/uni-app';
	const idImageFiles=ref([]);
	const licenseImage=ref([]);
	const shopImage=ref([]);
	const fileImage=ref([]);
	onLoad((query) => {
		console.log("query.id:",query.id)
		 //获取商户信息
		 if(query.id){
			http.request({
				url: "/X/application/getShop",
				method: "POST",
				data: {
					"id": query.id
				}
			}).then((responseData) => { 
				if(responseData.code==1){
					responseData.data.idImage=JSON.parse(responseData.data.idImage);
					responseData.data.files=JSON.parse(responseData.data.files);
					applicationContent.value= responseData.data; 
					const obj=responseData.data.idImage; 
					var idImageArr=[];
					for(var i=0;i<obj.length;i++){ 
						console.log(obj[i])
						idImageArr.push({
							url:obj[i]
						})
						idImage.value.push(obj[i]);
					}
					idImageFiles.value=idImageArr;
					console.log(idImageFiles.value)
					licenseImage.value={
						url:applicationContent.value.licenseImage
					}
					shopImage.value={
						url:applicationContent.value.shopImage
					}
					var filesObj=responseData.data.files; 
					files.value=filesObj;
					var filesarr=[];
					for(var i=0;i<filesObj.length;i++){ 
						filesarr.push(
							{url:filesObj[i]}
						)
					}
					fileImage.value=filesarr;
					console.log("fileImage",fileImage.value)
					region.value=responseData.data.province+"-"+responseData.data.city+"-"+responseData.data.district;
					service.value=responseData.data.service;
					menu.value=responseData.data.moduleName; 
				}
				console.log("applicationContent",applicationContent.value)
			}).catch((err) => {
				uni.showToast({
					icon: 'error',
					title: '请求失败'
				})
			}) 
		 } 
	}) 
	
	import {
		generateApplicationId,
		getCurrentTimestamp,
		generateTime
	} from '../../utils/timeUtils';
	const serviceArray = ref(['全国', '本省', '本市', '本小区'])
	const service = ref("请选择服务范围")
 
 
	// 提取字段
	const applicationContent = ref({
		userId: getApp().globalData.user.userId, 
		name: '', // 姓名
		sex: 0, // 性别
		phone: '', // 电话
		province: '',
		city: "",
		district: "",
		position: '', // 详细地址
		longitude: '', // 经度
		latitude: '', // 纬度
		service: '', // 服务范围
		module: '', // 选择模块
		tags: '', // 机构标签
		legalPersonName: '', // 法人姓名
		legalPersonIdCard: '', // 法人身份证号
		shopName: '', // 商户名称
		license: '', // 营业执照编码
		bankName: '', // 开户行
		bankCard: '', // 银行卡号
		idImage: [],
		licenseImage: "",
		files: [],
		shopImage:""
	});
	 
	// 所在区域
	var region=ref("请选择区域");
	function regionChange(e) {
		console.log(e)
		// console.log("position", e[0] + "-" + e[1] + "-" + e[2])
		// applicationContent.value.region = e[0] + "-" + e[1] + "-" + e[2]
		applicationContent.value.province = e.detail.value[0];
		applicationContent.value.city = e.detail.value[1];
		applicationContent.value.district = e.detail.value[2];
		region.value=e.detail.value[0]+"-"+e.detail.value[1]+"-"+e.detail.value[2];
	}
	// 详细地址
	const position = ref("")

	function updatePosition(e) {
		applicationContent.value.position = e.target.value;
	}
	// 选择地理位置
	const latitude = ref(39.909)
	const longitude = ref(116.39742)
	const isChooseMap = ref(false)

	function positionChange(e) {
		console.log("e", e)
		isChooseMap.value = true;
		applicationContent.value.latitude = e.latitude
		applicationContent.value.longitude = e.longitude
		applicationContent.value.addressName = e.name
		applicationContent.value.position = e.address
		position.value = e.address 
	}
	
	function selectAddress()
	{
		uni.chooseLocation({
			success(e){
				console.log(e);
				isChooseMap.value = true;
				applicationContent.value.latitude = e.latitude
				applicationContent.value.longitude = e.longitude
				applicationContent.value.addressName = e.name
				applicationContent.value.position = e.address
				position.value = e.address   
				latitude.value= e.latitude;
				longitude.value=e.longitude
				 // applicationContent.value.latitude = e.latitude
				 // applicationContent.value.longitude = e.longitude
				 // applicationContent.value.addressName = e.name
				 // applicationContent.value.position = e.address
				 // position.value = e.address 
				 
			},
			fail(res) {
				console.log(res);
				uni.showToast({
					icon: "none",
					title: "位置获取失败!"
				})
			}
		}) 
	}
	
	// 服务范围
	function serviceChange(e) {
		service.value = serviceArray.value[e.detail.value]
		applicationContent.value.service = serviceArray.value[e.detail.value]
	}
	// 选择模块
	function moduleChange(e) {
		module.value = moduleArray.value[e.detail.value]
		applicationContent.value.module = parseInt(e.detail.value) + 1
	}
	// 机构标签
	function tagChange(e) {
		applicationContent.value.tags = e.target.value;
	}

	function updateLegalPersonName(e) {
		applicationContent.value.legalPersonName = e.target.value;
	}

	function updateLegalPersonIdCard(e) {
		applicationContent.value.legalPersonIdCard = e.target.value;
	}
	 
	//身份证正面照片
	function handleIdSelect(e) {
		const tempFilePaths = e.tempFiles;
		for(var i=0;i<tempFilePaths.length;i++){
			upload(tempFilePaths[i],'idCard');
		} 
	}
	
	function handleIdDelete(e) {
		console.log("delete", e)
		idImage.value.splice(e.index, 1); // 移除数组中对应的文件
	}

	function handleLicenseSelect(e) { 
		const tempFilePaths = e.tempFiles;
		upload(tempFilePaths[0],'license');
	}

	function handleLicenseDelete(e) {
		applicationContent.value.licenseImage = ""
	}

	function handleShopImageSelect(e) { 
		const tempFilePaths = e.tempFiles;
		upload(tempFilePaths[0],'shopImage');
	}

	function handleShopImageDelete(e) {
		applicationContent.value.shopImage = ""
	}
	
	 
	const files=ref([]);
	function handleFileSelect(e) {
		 const tempFilePaths = e.tempFiles;
		 for(var i=0;i<tempFilePaths.length;i++){
			 upload(tempFilePaths[i],'files');
		 } 
	}

	function handleFileDelete(e) {
		files.value.splice(e.index, 1); // 移除数组中对应的文件
	} 
	const menuArr = ref();
	//类型
	const menu = ref('');
	const menuIndex = ref(0);
	function menuInt(){
		http.request({
			url: "/sys/menu/list",
			method: "POST",
			data: {
				"pid": 0,
				isShow:1
			}
		}).then((responseData) => { 
			 if(responseData.code==1){
				 menuArr.value=responseData.data;
				 console.log(menuArr.value)
			 }
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			})
		})
	}
	menuInt(); 
	function menuChange(e) {
		const index = e.detail.value;
		menu.value = menuArr.value[index].name;
		menuIndex.value = menuArr.value[index].id;
		applicationContent.value.module=menuArr.value[index].id;
	}
	const idImage=ref([]); 
	function upload(tempFilePaths,type){
		uni.showLoading({
			title: '图片上传中',
			mask:true
		});
		uni.uploadFile({
			url: getApp().globalData.upLoadUrl,
			filePath: tempFilePaths.path,
			name: 'file', // 文件字段名
			formData: {
				"fileType": "application",
				"fileName": getCurrentTimestamp(),
				"userId": applicationContent.value.userId
			},
			success: (uploadRes) => { 
				uni.hideLoading();
				console.log(uploadRes.data);
				let jsonData = JSON.parse(uploadRes.data);
				if(jsonData.code==1){
					if(type=='idCard'){
						idImage.value.push(jsonData.data);
					}else if(type=='license'){
						applicationContent.value.licenseImage=jsonData.data;
					}else if(type=='shopImage'){
						applicationContent.value.shopImage=jsonData.data;
						console.log("11111111111111111111111111111111",applicationContent.value)
					} else{
						files.value.push(jsonData.data);
					}
				}else{
					uni.hideLoading();
					uni.showToast({
						title: '图片上传失败',
					    icon:'error',
						duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
					    mask:true
					});
				}
			},
			fail: (error) => {
				uni.showToast({
					title: '图片上传失败',
				    icon:'error',
					duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
				    mask:true
				});
			}
		});
	}

 
 
 
	async function submit() {
		if(!xieYiV.value){
			uni.showToast({
				icon: 'error',
				title: '请阅读协议'
			})
			return;
		}
		 try {
		 	applicationContent.value.idImage= JSON.stringify(idImage.value)
		 	applicationContent.value.files= JSON.stringify(files.value);
			console.log(applicationContent.value);
			
			 
		 	// 所有上传操作完成后，调用 http.request 
		 	uni.showLoading({
		 		title: '提交中',
		 		mask:true
		 	});
		 	
		 	http.request({
		 		url: "/X/application/shop",
		 		method: "POST",
		 		data: {
		 			shop: applicationContent.value
		 		}
		 	}).then((res) => { 
		 		console.log(res);
		 		uni.hideLoading();
		 		if(res.code==1){ 
					 getApp().globalData.user.shop=2;
					 
					 uni.showModal({
					 	title: '提示',
					 	content: '资料已提交，请在1个工作日后查看是否通过；如未通过请按要求修改；如已通过，请在后台申请中申请账号，用于平台所有后台登录。',
						showCancel:false,
					 	success: function (res) {
					 		if (res.confirm) {
					 			wx.switchTab({
					 			  url: "/pages/my/my",
					 			  success: function(res) {
					 			    // 跳转成功
					 			  },
					 			  fail: function(err) {
					 			    // 错误处理
					 			  }
					 			})
					 		} else if (res.cancel) {
					 			console.log('用户点击取消');
					 		}
					 	}
					 });
					 
		 			
		 		}else if(res.code==0){
		 			 uni.showToast({
		 			 	icon: 'error',
		 			 	title: res.message
		 			 })
		 		}else if(res.code==-1){
		 			uni.navigateTo({
		 				url: "/pages/login/login"
		 			});
		 		}
		 	}).catch((err) => {
		 		uni.showToast({
		 			icon: 'error',
		 			title: '请求失败'
		 		})
		 	}) 
		 	
		 } catch (err) {
		 	// 在这里处理上传文件过程中的错误
		 	console.log("上传文件失败", err);
		 }
	}
 
</script>

<style>
	@import "./form.scss";
	Page{
		  background: white;
	}
</style>